<template>
  <div class="menu-content">
    <!-- 搜索栏卡片 -->
    <el-card class="card-container search-card">
      <div class="search-container">
        <!-- 添加@input和@clear事件 -->
        <el-input v-model="searchParams.equipmentId" placeholder="请输入搜索的设备ID" class="search-input" clearable
          @input="handleSearch" @clear="handleSearch">
          <template #prefix>
            <el-icon class="el-input__icon">
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" class="search-button" @click="handleSearch">搜索</el-button>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="card-container table-card">
      <el-table :data="completedRepairs" stripe border class="custom-table rounded-table" v-loading="loading">
        <!-- 修复完成时间显示格式 -->
        <el-table-column prop="completeTime" label="完成时间" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.completeTime) }}
          </template>
        </el-table-column>
        <!-- 添加订单创建时间列 -->
        <el-table-column prop="createTime" label="订单创建时间" align="center"></el-table-column>
        <el-table-column prop="equipmentId" label="设备ID" align="center"></el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" align="center"></el-table-column>
        <el-table-column prop="remark" label="维修备注" align="center">
          <template #default="scope">
            <el-button type="text" @click="openRemarkDialog(scope.row.remark)">查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已完成' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          layout="total, prev, pager, next, jumper" :prev-text="'上一页'" :next-text="'下一页'"
          @current-change="handleCurrentChange">
          <template #format-total="{ total }">
            总计 {{ total }} 条
          </template>
        </el-pagination>
      </div>
    </el-card>

    <!-- 维修备注详情弹窗 -->
    <el-dialog v-model="showRemarkDialog" title="维修备注详情" width="500px" :close-on-click-modal="false">
      <div class="remark-content">
        <p v-if="!currentRemark" class="empty-remark">暂无维修备注信息</p>
        <pre v-else>{{ currentRemark }}</pre>
      </div>
      <template #footer>
        <el-button @click="showRemarkDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
// 修复：将导入名称从request改为service，与request.js导出保持一致
import service from '@/utils/request';
import { ElMessage, ElTag, ElDialog, ElButton } from 'element-plus';

export default {
  name: 'FaultProgress',
  components: { Search, ElTag, ElDialog, ElButton },
  setup() {
    // 状态管理
    const completedRepairs = ref([]);
    const loading = ref(false);
    const showRemarkDialog = ref(false);
    const currentRemark = ref('');
    const searchParams = ref({ equipmentId: '' });

    // 分页控制
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 添加日期格式化函数
    // 增强日期格式化函数，增加容错处理
    const formatDate = (dateString) => {
      console.log('原始日期值:', dateString);
      if (!dateString) return '无数据';
      try {
        // 尝试标准日期解析
        const date = new Date(dateString);
        if (!isNaN(date.getTime())) {
          // 格式化日期为 YYYY-MM-DD HH:MM:SS
          return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
        }
        // 直接替换T字符作为备选方案
        return dateString.replace('T', ' ');
      } catch (error) {
        console.error('日期格式化错误:', error);
        return dateString || '格式错误';
      }
    };

    // 获取已完成维修订单数据
    const fetchCompletedRepairs = async () => {
      loading.value = true;
      try {
        // 构建查询参数，仅在equipmentId有值时传递
        const queryParams = {
          page: currentPage.value,
          size: pageSize.value
        };
        // 仅当equipmentId不为空时添加该参数
        if (searchParams.value.equipmentId) {
          queryParams.equipmentId = searchParams.value.equipmentId;
        }

        const response = await service.get('/users/getMyCompletedRepair', {
          params: queryParams
        });
        console.log('完整API响应:', response);
        // 调整数据解析逻辑以适应不同后端格式
        const responseData = response.data || {};
        // 尝试多种常见数据路径
        const dataList = responseData.data?.list || responseData.list || responseData || [];
        const dataTotal = responseData.data?.total || responseData.total || dataList.length;

        // 添加前端精确匹配过滤
        const filteredList = searchParams.value.equipmentId
          ? dataList.filter(item => item.equipmentId === searchParams.value.equipmentId)
          : dataList;

        completedRepairs.value = filteredList;
        total.value = filteredList.length;

        console.log('解析后的数据:', { list: dataList, total: dataTotal });
        if (dataList.length === 0) {
          ElMessage({ message: '未查询到维修订单数据', type: 'info' });
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取数据失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1; // 重置页码
      fetchCompletedRepairs();
    };

    // 分页变化处理
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchCompletedRepairs();
    };

    // 打开备注详情
    const openRemarkDialog = (remark) => {
      currentRemark.value = remark;
      showRemarkDialog.value = true;
    };

    // 初始化加载数据
    onMounted(() => {
      fetchCompletedRepairs();
    });

    return {
      completedRepairs,
      loading,
      searchParams,
      currentPage,
      pageSize,
      total,
      showRemarkDialog,
      currentRemark,
      handleSearch,
      handleCurrentChange,
      openRemarkDialog,
      formatDate // 导出格式化函数
    };
  }
};
</script>

<style scoped>
/* 添加卡片容器样式 */
.card-container {
  width: 70%;
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-card {
  padding: 20px;
  margin-top: 20px;
}

.table-card {
  padding: 20px;
}

/* 搜索容器样式 */
.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 0;
  width: 100%;
  align-items: center;
}

.search-input {
  width: calc(100% - 100px);
  max-width: 100%;
}

.search-button {
  width: 80px;
}

/* 表格样式 */
::v-deep .custom-table {
  width: 100%;
  min-height: 400px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e8e8e8;
}

/* 表格圆角样式 */
::v-deep .rounded-table {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: none !important;
}

/* 表头样式 - 保持不变 */
::v-deep .custom-table .el-table__header-wrapper th {
  background-color: #1890ff !important;
  color: white !important;
  font-weight: 500;
  border-bottom: 2px solid white !important;
}

/* 表格行基础样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row {
  transition: all 0.2s ease;
  position: relative;
}

/* 表格行悬浮效果 - 三级选择器保障 */
/* 第一级：表格行悬浮基础样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover {
  transform: scale(1.01);
  transform-origin: center left;
  background-color: #1890ff !important;
  color: #fff !important;
  font-size: 15px;
  z-index: 10;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 0 5px;
}

/* 第二级：增强特异性 */
::v-deep .custom-table .el-table__body .el-table__row:hover {
  background-color: #1890ff !important;
  color: #fff !important;
}

/* 第三级：单元格样式保障 */
::v-deep .el-table__body tr.el-table__row:hover>td {
  background-color: #1890ff !important;
  color: #fff !important;
}

/* 确保表格有足够宽度容纳放大后的内容 */
::v-deep .el-table__body {
  width: 100% !important;
}

/* 悬浮行中的文本按钮文字变白 */
::v-deep .el-table__row:hover .el-button--text {
  color: #fff !important;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
  position: static;
  bottom: auto;
  left: auto;
  transform: none;
  background-color: transparent;
  padding: 0;
  box-shadow: none;
}

/* 维修备注详情弹窗样式 */
.remark-content {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.empty-remark {
  color: #909399;
  text-align: center;
  padding: 20px;
}
</style>